package com.crm.miaohe.service;

import com.crm.miaohe.controller.report.response.OrderReportWeek;
import com.crm.miaohe.mapper.TblOrderMapper;
import com.crm.miaohe.model.TblOrder;
import com.crm.miaohe.model.TblOrderExample;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.WeekFields;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("weekOrderReportService")
public class OrderWeekReportService implements OrderReportService<OrderReportWeek> {

    private TblOrderMapper tblOrderMapper;

    public OrderWeekReportService(TblOrderMapper tblOrderMapper){
        this.tblOrderMapper = tblOrderMapper;
    }

    @Override
    public OrderReportWeek orderReport() {

        WeekFields weekFields = WeekFields.of(DayOfWeek.MONDAY, 1);
        LocalDate startDayOfCurrentWeek = LocalDate.now().with(weekFields.getFirstDayOfWeek());
        LocalDateTime start = startDayOfCurrentWeek.atStartOfDay();
        LocalDateTime end = startDayOfCurrentWeek.plusDays(7).atStartOfDay();
        TblOrderExample orderExample = new TblOrderExample();
        orderExample.createCriteria().andCreateTimeGreaterThanOrEqualTo(start).andCreateTimeLessThan(end).andStatusEqualTo(1);
        List<TblOrder> tblOrderList = tblOrderMapper.selectByExample(orderExample);

        List<Map.Entry<LocalDate, List<TblOrder>>> entries = tblOrderList.stream()
                .collect(Collectors.groupingBy(tblOrder -> tblOrder.getCreateTime().toLocalDate()))
                .entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
        int dayOfWeek = 0, index = 0, entrySize = entries.size();
        OrderReportWeek history = new OrderReportWeek();
        while (dayOfWeek <= 6 && index < entrySize) {
            Map.Entry<LocalDate, List<TblOrder>> entry = entries.get(index);
            LocalDate day = startDayOfCurrentWeek.plusDays(dayOfWeek);
            if (entry.getKey().equals(day)) {
                history.getAlertWeekHistory().add(BigInteger.valueOf(entry.getValue().size()));
                index++;
            } else {
                history.getAlertWeekHistory().add(BigInteger.ZERO);
            }
            dayOfWeek++;
        }
        List<BigInteger> historyData = history.getAlertWeekHistory();
        while (historyData.size() < 7) {
            historyData.add(BigInteger.ZERO);
        }

        return history;
    }
}
